
var wyx_popup_dialog = null;
var image_info = null;

function click_showDialog(left, top) {
  if(wyx_popup_dialog) {
	click_deactivate();
  }

  wyx_popup_dialog = document.createElement("iframe");
  wyx_popup_dialog.src = chrome.extension.getURL("popup.html");
  wyx_popup_dialog.setAttribute("style", "position: fixed !important; visibility: hidden; display: block !important; border: 0px !important;");
  wyx_popup_dialog.style.WebkitBoxShadow = "5px 5px 20px rgba(0,0,0,0.5)";
  wyx_popup_dialog.style.zIndex = 99999;

  // Position in upper-left all the time
  wyx_popup_dialog.style.left = left + "px";
  wyx_popup_dialog.style.top = top + "px";

  wyx_popup_dialog.onmouseout = function() {
    if (wyx_popup_dialog)
      wyx_popup_dialog.style.setProperty("opacity", "0.6");
  }
  wyx_popup_dialog.onmouseover = function() {
    if (wyx_popup_dialog)
      wyx_popup_dialog.style.setProperty("opacity", "1.0");
  } 
  
  document.body.appendChild(wyx_popup_dialog);
}

function click_deactivate() {
  if (wyx_popup_dialog) {
    document.body.removeChild(wyx_popup_dialog);
    wyx_popup_dialog = null;
  }
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
{
    switch (request.type)
    {
	  case "create-dialog":
	    image_info = request.img;
        click_showDialog(50, 50);
        break;

	  case "init-dialog": {
		  image_info.referrer = location.href;
          image_info.cookie = document.cookie;
          image_info.title = document.title;
		  image_info.from_protocol = location.protocol;
		  image_info.from_domain = location.host;
		  image_info.from_page = location.pathname+location.search;
		  // console.log(image_info);
          sendResponse(image_info);
        }
		break;

	  case "ajust-dialog":
		var height = request.height>500?500:request.height;
		if (wyx_popup_dialog) {
		  wyx_popup_dialog.style.width = (request.width +20) + "px";
          wyx_popup_dialog.style.height = (height) + "px";
          wyx_popup_dialog.style.visibility = "visible";
	    }
		sendResponse({height: height});
		break;
      
      // not used
      case "click-tomove":
        //if (wyx_popup_dialog)
        //{
        //  wyx_popup_dialog.style.left = (parseInt(wyx_popup_dialog.style.left, 10) + request.x) + "px";
        //  wyx_popup_dialog.style.top = (parseInt(wyx_popup_dialog.style.top, 10) + request.y) + "px";
        ///}
        break;

      case "click-close":
        click_deactivate();
        break;

      default:
        sendResponse({});
        break;
    }
});